package com.yanqu.road.server.timer.ghost;

import com.yanqu.road.entity.activity.ghost.GhostData;
import com.yanqu.road.entity.activity.ghost.config.GhostConfig;
import com.yanqu.road.pb.activity.GhostActivityProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.cross.battle.ghost.GhostActivity;
import com.yanqu.road.server.manager.cross.battle.ghost.GhostMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GhostGetAbilityTask extends GeneralTask {

    @Override
    public void doRun() {

        long now = System.currentTimeMillis();

        // 移除旧活动
        List<Integer> activityIdList = new ArrayList<>();
        long expireTime = now / 1000 - 10L * 60L; // 结束10分钟后
        for (Map.Entry<Integer, GhostActivity> activityEntry : GhostMgr.getActivityMap().entrySet()) {
            if (activityEntry.getValue().getGhostConfig().getActivityInfo().getEndShowTime() < expireTime) {
                activityIdList.add(activityEntry.getKey());
            }
        }
        for (Integer activityId : activityIdList) {
            GhostMgr.getActivityMap().remove(activityId);
        }


        // 获取区服能力值
        for (GhostActivity activity : GhostMgr.getActivityMap().values()) {
            GhostConfig ghostConfig = activity.getGhostConfig();
            GhostData ghostData = activity.getGhostData();
            if (ghostData.getLastResetTime() > 0) {
                continue;
            }
            List<Long> serverList = StringUtils.stringToLongList(ghostConfig.getActivityInfo().getServerListStr(), ",");
            for (long serverId : serverList) {
                if (!ghostData.getAbilityMap().containsKey(serverId)) {
                    GhostActivityProto.NotifyUploadAbilityReqMsg.Builder builder = GhostActivityProto.NotifyUploadAbilityReqMsg.newBuilder();
                    builder.setActivityId(ghostConfig.getActivityId());
                    MessageHelper.sendPacket(serverId, -1, YanQuMessageUtils.buildMessage(GameProtocol.S_GHOST_NOTIFY_UPLOAD_ABILITY, builder));
                }
            }
        }

        // 跨服数据重置（用户触发）
//        for (GhostActivity activity : GhostMgr.getActivityMap().values()) {
//            try {
//
//                activity.checkDailyResetData();
//
//            } catch (Exception e) {
//                int activityId = -1;
//                if (activity != null && activity.getGhostConfig() != null) {
//                    activityId = activity.getGhostConfig().getActivityId();
//                }
//                getLOGGER().error("Ghost Get Ability Task error on daily reset. activityId={}, errorMsg={}",
//                        activityId, e.getMessage());
//            }
//        }

    }
}
